/*
* @Author: Administrator
* @Date:   2018-01-27 14:54:09
* @Last Modified by:   Administrator
* @Last Modified time: 2018-01-27 16:36:56
*/
const ReeactDomServer = require('react-dom/server')
const preset = require('jss-preset-default').default
const Helmet = require('react-helmet').default
const asyncBootstrapper = require('react-async-bootstrapper').default
const serializeJs = require('serialize-javascript')

const createMuiTheme = require('material-ui/styles/createMuiTheme').default
const { deepOrange, blue } = require('material-ui/colors')
const { create } = require('jss')
const { SheetsRegistry } = require('react-jss')
const esj = require('ejs')

const getStoreState = (stores) => {
  return Object.keys(stores).reduce((result, storeName) => {
    result[storeName] = stores[storeName].toJson()
    return result
  }, {})
}

const serverRender = (bundleModule, template, req, res) => {
  return new Promise((resolve, reject) => {
    const createApp = bundleModule.default
    const createStores = bundleModule.createStores
    const stores = createStores()
    const jss = create(preset())
    const sheetsRegistry = new SheetsRegistry()
    const theme = createMuiTheme({
      palette: {
        primary: deepOrange,
        accent: blue,
        type: 'light',
      }
    })
    const context = {}
    const app = createApp(stores, context, req.url, theme, sheetsRegistry, jss)
    if (context.url) {
      res.status(302).setHeader('Location', routerContext.url)
      res.end()
      return
    }
    stores.user.userInfo = Object.assign({}, req.session.user)
    delete stores.user.userInfo.accessToken
    asyncBootstrapper(app).then(() => {
      const content = ReeactDomServer.renderToString(app)
      const helmet = Helmet.rewind()
      const html = esj.render(template,{
        content: content,
        jssStyle: sheetsRegistry.toString(),
        initialStore: serializeJs(getStoreState(stores)),
        title: helmet.title.toString(),
      })
      res.send(html)
      resolve()
    }).catch((e) => {
      reject(e)
    })
  })
}

module.exports = serverRender
